package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.domain.SystemMenu;
import cn.wolfcode.wms.mapper.SystemMenuMapper;
import cn.wolfcode.wms.page.PageResult;
import cn.wolfcode.wms.qo.QueryObject;
import cn.wolfcode.wms.service.ISystemMenuService;
import cn.wolfcode.wms.util.UserContext;
import cn.wolfcode.wms.vo.SystemMenuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class SystemMenuServiceImpl implements ISystemMenuService {

    @Autowired
    private SystemMenuMapper systemMenuMapper;

    public List<SystemMenu> listAll() {

        return systemMenuMapper.selectAll();
    }

    public SystemMenu getById(Long id) {

        return systemMenuMapper.selectByPrimaryKey(id);
    }

    public void saveOrUpdate(SystemMenu systemMenu) {
        if (systemMenu.getId() != null) {
            systemMenuMapper.updateByPrimaryKey(systemMenu);
        } else {
            systemMenuMapper.insert(systemMenu);
        }
    }

    public void delete(Long id) {

        //删除自身之前删除子菜单
        systemMenuMapper.deleteByParentId(id);
        systemMenuMapper.deleteByPrimaryKey(id);
    }

    public PageResult query(QueryObject qo) {
        int rows = systemMenuMapper.queryForCount(qo);
        if (rows == 0) {
            return PageResult.empty(qo.getPageSize());
        }
        List<?> result = systemMenuMapper.queryForList(qo);
        return new PageResult(rows, result, qo.getCurrentPage(), qo.getPageSize());
    }

    public List<SystemMenu> getParents(Long parentId) {
        List<SystemMenu> ret = new ArrayList<>();
        //判断parentId不为null
        while (parentId != null) {
            SystemMenu parent = systemMenuMapper.selectByPrimaryKey(parentId);
            if (parentId != null) {
                ret.add(parent);
                parent = parent.getParent();
                if (parent != null) {
                    parentId = parent.getId();
                }
            }
            if (parent == null) {
                break;
            }
        }
        Collections.reverse(ret);
        return ret;
    }

    public List<SystemMenuVO> loadMenuByParentSn(String parentSn) {
        //获取当前登录用户
        Employee currentUser = UserContext.getcurrentUser();
        //判断该用户是否是超级管理员,如果是直接返回所有菜单
        if (currentUser.isAdmin()){
            return systemMenuMapper.loadMenuByParentSn(parentSn);
        }
        return systemMenuMapper.loadMenuByParentSnAndEmpId(parentSn,currentUser.getId());
        //根据当前用户所拥有的角色去查询对应的菜单
    }
}
